package com.wms.controller;


import com.wms.config.Result;
import com.wms.service.RedisService;
import com.wms.util.CaptchaUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("captcha")
@CrossOrigin
public class CaptchaController {
    private final CaptchaUtil captchaUtil;

    public CaptchaController(CaptchaUtil captchaUtil) {
        this.captchaUtil = captchaUtil;
    }
    @Autowired
    RedisService redisService;


    @RequestMapping("line")
    public Result getLineCaptcha(HttpServletResponse response) {
        String[] arr = captchaUtil.getLineImage();
        String key = arr[0];
        String base64 = arr[1];
//        Cookie cookie = new Cookie("captchakey", key);
//        response.addCookie(cookie);
        return Result.success("成功更新验证码",key+"+data:image/jpeg;base64,"+base64);
    }

    @RequestMapping("check")
    public Result checkCaptcha(HttpServletRequest request, @RequestParam("captchaCode") String captchaCode) {
        Cookie[] cookies = request.getCookies();
        String key = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("captchakey")) {
                key = cookie.getValue();
                break;
            }
        }
        if (key == null) {
            return Result.fail(400, "请求参数异常");
        }
        String code = (String) redisService.get(key);
        if (code == null) {
            return Result.fail(201, "验证码已过期");
        }
        if (captchaCode.equals(code)) {
            return Result.success("验证码正确", true);
        }
        return Result.fail(400, "验证失败");
    }

}
